package com.medicalproject.service.impl;

import com.medical.pojo.User;
import com.medicalproject.demo.SendSms;
import com.medicalproject.mapper.UserMapper;
import com.medicalproject.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    RedisTemplate redisTemplate;
    @Override
    public User login(String username, String password) {
        return userMapper.login(username,password);
    }

    @Override
    public List<User> findAll() {
        return userMapper.findAll();
    }

    @Override
    public User login2(String phone, String code) {
        code=redisTemplate.boundValueOps("121212").get().toString();
        if (code==null){
            return null;
        }
        if (!code.equals(code)){
            return null;
        }else {
            return userMapper.login2(phone,code);
        }

    }

    @Override
    public void update(String phone, String code) {
        userMapper.update(phone,code);
    }

    @Override
    public void add(User user) {
        userMapper.add(user);
    }

    @Override
    public String sendcode(String phone) {
        String code = String.valueOf(generateRandomCode());
        redisTemplate.boundValueOps("121212").set(code, 1, TimeUnit.MINUTES);
        try {
            SendSms.main(phone,code);
            User phone1 = userMapper.findPhone(phone);
            log.info("phone1="+phone1);
            userMapper.update(phone,code);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        return code;
    }

    private static int generateRandomCode() {
        Random random = new Random();
        int randomNumber = random.nextInt(9000) + 1000; // 生成1000到9999之间的随机数
//        redisTemplate.boundValueOps("code_").set(randomNumber, 5, TimeUnit.MINUTES);

        return randomNumber;


    }


}
